<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ajax</title>
  </head>
  <body>
    <script>
      function ajaxRequest(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "json";
        xhr.onload = function () {
          callback(null, xhr.response);
        };
        xhr.send();
      }

      function requests(urls, callback) {
        //用来存放最终的结果
        let result = [];
        //已经完成的总请求数
        let completedRequests = 0;
        //总请求数
        let totalRequests = urls.length;
        function handleResponse(data, index) {
          result[index] = data;
          if (++completedRequests === totalRequests) {
            callback(null,result)
          }
        }
        urls.forEach((url,index)=>{
          ajaxRequest(url, function (err, data) {
            handleResponse(data, index);
          });
        });
      }
      requests(
        ["data1.json", "data2.json", "data3.json"],//data1 3s data2 2s data3 1s
        function (err, result) {
          console.log(result);//[data1,data2,data3]
        }
      );
    </script>
  </body>
</html>
